package al141hasCycle;

class ListNode {
    int val;
    ListNode next;

    // 构造函数
    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class HasCycle141 {

    public static boolean hasCycle(ListNode head) {

        if (head ==null ||head.next==null) {
            return false;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast !=null && fast.next!=null){
            if (fast==slow) {
                return true;
            }
            slow=slow.next;
            fast=fast.next.next;
        }
        return false;
    }

    public static void main(String[] args) {
        // 创建链表：1 -> 2 -> 3 -> 4 -> 5 -> 6
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;

        // 测试无环链表
        System.out.println("Test case 1 (No Cycle): " + hasCycle(node1)); // 应该输出 false

        // 创建一个有环的链表：1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 3 (形成环)
        node6.next = node3; // 让链表形成一个环

        // 测试有环链表
        System.out.println("Test case 2 (Has Cycle): " + hasCycle(node1)); // 应该输出 true
    }
}
